<?php
/****
* 活动详情模块, 包含 显示\用户动作(关注, 参与)\编辑 等
****/
import('@.Model.Extend.EventViewModel');
import('@.Model.Where.MarkWhereMachine');
import('@.Model.Extend.EventMarker');
import('@.Model.Extend.EventAlbum');
class EventAction extends InitAction{
    protected function _initialize(){
        parent::_initialize();
    }
    public function index(){
        $e= $this->getCurrentEvent();        
        
        //是否已经关注  
        if ($uid= $this->isLogged()){
            $map= array(
                        'uid'=> $uid,
                        'eid'=> $e['id'],
                    );
            $mark= M('EventMark')->where($map)->find();
            if ($mark){
                $e['wish']= $mark['wish'];
                $e['take']= $mark['take'];
            }
                
        }
        //转换BBCode
        import('@.Common.NoticeBBCode');
        $bbcode = new NoticeBBCode();
        $e['content']= $bbcode->Parse($e['content']);
        
        //获取该活动的关注人员
        $markerMap= new MarkWhereMachine();
        $markerMap->id($e['id'])->isTake();
        $markerM= new EventMarker();
        $taker= $markerM->where($markerMap->get())->limit(12)->select();
        $this->assign('takers', $taker);
        
        //trick:统计人数
        $e['cnt_take']= M('EventMark')->where($markerMap->get())->count();
        $markerMap->reset();
        $markerMap->id($e['id'])->isWish();
        $e['cnt_wish']= M('EventMark')->where($markerMap->get())->count();
        
        //获取tag
        $etm= new EventTagModel();
        $tag= $etm->where('eid ='.$e['id'])->field('tag')->select();
        foreach($tag as &$v){       //转换为简单数组
            $v=$v['tag'];
        }
        $e['tag']=$tag;
        $this->assign('event', $e);
        
        $this->assign('hot', $this->mockgetHot());
        //活动照片
        $albumM= new EventAlbum($e['id'], $uid);
        $this->assign('album', $albumM->getAlbum(0, 8));
        $this->display('index');
    }
    /****
    * 添加
    */
	public function create(){
        if (! $uid=$this->isLogged()){
            $this->error("请先登录");
            return false;
        }
        if (! isset($_POST['submit'])){
            $t= time();
            $e= array(
                'start_date'=>date('Y-m-d', $t),
                'start_time'=>date('H:00', $t),
                'end_date'=>date('Y-m-d', $t+3600*4),
                'end_time'=>date('H:00', $t+3600*4),
            );
            $this->assign('event', $e);
            $this->display('edit');
            return;
        }
        //进行实际的插入操作
        $data= $this->wrapRequest($_REQUEST);
        $data['author_id']= $uid;
        $imginfo= $this->handleUpload();
        if (!is_null($imginfo)){
            $data['img']= $imginfo[0]['savename'];
        }
        $em= D('Event');
        //$em->startTrans();
        /*
        if ($vo= $em->create($data)){

            if ($eid= $em->add()){
                //$em->commit();
                
                $this->assign("jumpUrl",__URL__.'/'.$eid);
                $this->success("插入成功");
                ////$this->ajaxReturn($vo, "数据插入成功", 1);
            } else{
                //$em->rollback();
                
                $this->error("数据插入错误");
            }
        } else{
            $this->error($em->getError());
        }*/
        $vo= $em->create($data);
        ////TODO        
        if (! $vo){
            $this->error($em->getError());
            return false;
        }
        if (! $eid= $em->add()){
            $this->error("数据插入错误");
            return false;
        }
        $res=$em->setTag($_REQUEST['tag'], $eid);
        $this->assign("jumpUrl",U("/event/$eid"));
        $this->success("创建成功");
    }
    /****
    * 编辑
    */
    public function edit(){
        $this->checkID($uid, $eid);
        if (! isset($_POST['submit'])){
            $e= $this->prepEditView($eid);
            
            $this->display();
            return;
        } else{
            $data= $this->wrapRequest($_REQUEST);
            $imginfo= $this->handleUpload();
            if (!is_null($imginfo)){
                $data['img']= $imginfo[0]['savename'];
            }
            //$data['author_id']= $uid;
            $em= new EventModel();
            $vo= $em->create($data);
            if (! $vo){
                $this->error($em->getError());
                return false;
            }
            
            
            //tag
            $res=$em->setTag($_REQUEST['tag'], $eid);
            $eid= $em->save($data);
            if (false=== $eid){
                $this->error("数据插入错误");
                return false;
            }
            $eid= $vo['id'];
            $this->assign("jumpUrl",U("/event/$eid"));
            $this->success("修改成功");
        }
    }
    /****
    * 参加
    */
    public function take(){
        //TODO ajaxreturn
        $this->checkID($uid, $eid);
        $EMark= D('EventMark');
        $data=M('Event')->find($eid);
        $res= $EMark->takeEvent($uid, $eid, $data);
        
        if (false===$res){
            $this->error("take失败");
        } else{
            if ($this->isAjax()){
                $this->success("成功");
            }else{
                redirect(__URL__.'/'.$eid);
            }
        }
    }
    /****
    * 关注
    */
    public function wish(){
        //TODO ajaxreturn
        $this->checkID($uid, $eid);
        $EMark= D('EventMark');
        $data=M('Event')->find($eid);
        $res= $EMark->wishEvent($uid, $eid, $data);
        
        if (false===$res){
            $this->error("wish失败");
        } else{
            if ($this->isAjax()){
                $this->success("成功");
            }else{
                redirect(__URL__.'/'.$eid);
            }
        }
    }
    public function mockgetHot(){
        $e= M('Event')->order('`id` DESC')->limit(5)->select();
        return $e;
    }
    /****
    * 上传图片
    * @imgfile 文件
    * @imgtype 可以为poster或者image，存到不同路径下
    */
    protected function handleUpload($imgtype=null){
        //realpath('./')= thinkPHP项目的index.php入口所在路径
        import('@.Common.NoticeImageUploader');
        if ($_FILES['imgfile']['size']<=1){
        //没有选择文件，则跳过
            return null;
        }
        $uploader= new NoticeImageUploader();
        if (! $imgtype){
            $imgtype= $_POST['imgtype'];
            //$path应当以/结尾
        }
        $rea= false;
        if ($imgtype== NoticeImageUploader::C('TYPE_POSTER')){
            $res= $uploader->uploadEventPoster();
        } else if ($imgtype==NoticeImageUploader::C('TYPE_EVENT_IMAGE')){
            $res= $uploader->uploadEventImage();
        }
        
        if(! $res) { // 上传错误 提示错误信息   
            $this->error($uploader->getErrorMsg());
            return false;
        }else{ // 上传成功 获取上传文件信息   
            $info =  $uploader->getUploadFileInfo(); 
            $_POST['img']  = $info[0]['savename'];            
        }
        return $info;
    }
    /****
    * 同时检测活动存在性和用户已登录
    */
    protected function checkID(&$uid, &$eid){
        if (! $eid=$_GET['id']){
            $this->error("错误的ID");
            return false;
        }
        if (! $uid=parent::isLogged()){
            $this->error("请先登录");
            return false;
        }
    }
    /****
    * 对将要显示在 活动编辑\创建 页面上的内容进行预处理
    *****/
    protected function prepEditView($eid){
        $em= D('Event');
        $e= $em->find($eid);
        if (!$e){
            $this->error("错误的ID");
        }
        $uid= parent::isLogged();
        if ($e['author_id'] !=$uid){
            $this->error("没有足够的访问权限");
        }
        
        $t= strtotime($e['time_start']);
        if (false !== $t){
            $e['start_date']= date('Y-m-d', $t);
            $e['start_time']= date('H:i', $t);
        }
        $t= strtotime($e['time_end']);
        if (false !== $t){
            $e['end_date']= date('Y-m-d', $t);
            $e['end_time']= date('H:i', $t);
        }
        $etm= new EventTagModel();
        $tag= $etm->where('eid ='.$eid)->field('tag')->select();
        $str= '';
        foreach( $tag as $v){
            $str.=$v['tag'].',';
        }
        $e['tags']= substr($str, 0, -1);    //去掉末尾的,
        
        $this->assign('event', $e);
        //$this->assign('EVENT_TYPE', L('EVENT_TYPE'));
        return $e;
    }
    /****
    * 提交表单的预处理
    */
    protected function wrapRequest($raw =null){
        if (is_null($raw)){
            $raw= $_POST;
        }
        $reqMap= array(
            'uid'   =>'author_id',
            'title' =>'title',
            'loc'   =>'location',
            'img'   =>'img',
            'type'  =>'type',
            'content'   =>'content',
            /*'start_data' =>'time_start',
            'start_time' =>'time_start',
            'end_data'   =>'time_end',
            'end_time'   =>'time_end',
            */
            //'tag'   =>'tag',
            //'state'    =>'visibility',
        );
        $res= $raw;
        Notice::Remap($res, $reqMap);
        //统一使用local time
        //TODO: check datetime format
        if (strlen($raw['start_date'])<6 || strlen($raw['start_time'])<3){
            return false;
        } else{
            //$res['start_time']= gmdate(DATE_ATOM, strtotime($raw['start_date'].' '.$raw['start_time']));  //转换为GMT时间
            $res['time_start']= date(DATE_ATOM, strtotime($raw['start_date'].' '.$raw['start_time']));
        }
        if (strlen($raw['end_date'])>=6 && strlen($raw['end_time'])>=3){
            //$res['end_time']= gmdate(DATE_ATOM, strtotime($raw['end_date'].' '.$raw['end_time']));
            $res['time_end']= date(DATE_ATOM, strtotime($raw['end_date'].' '.$raw['end_time']));
        }
        if ($res['time_end']<$res['time_start']){
            $this->error("错误的活动结束时间");
            return false;
        }
        if (isset($res['state'])){
            $res['visibility']= EventModel::C('STATE_NORMAL');
        } else{
            $res['visibility']= EventModel::C('STATE_HIDDEN');
        }
        //增入外键role
        $res['role']= $this->account['role'];
        
        //分割tag
        //$res['tag_array']= preg_split(', *', $res['tag']);
        
        return $res;
    }
    protected function getCurrentEvent(){
        $eid= $_GET['id'];
        if (is_null($eid)){
            $this->error("错误的参数");
        }
        $em= new EventViewModel();
        $e= $em->find($eid);
        if (! $e){
            $this->error("未找到相应条目");
            return false;
        }
        $e['author_profile']= __APP__.'/user/'.$e['author_id'];
        
        return $e;
    }
}
?>